package com.zmc.admin.application.impl;

import com.zmc.admin.application.RoleApplicationService;
import com.zmc.admin.infrastructure.constant.ErrorCodeConstants;
import com.zmc.admin.infrastructure.entity.SysRoleEntity;
import com.zmc.admin.infrastructure.entity.SysRoleMenuEntity;
import com.zmc.admin.infrastructure.service.SysRoleMenuService;
import com.zmc.admin.infrastructure.service.SysRoleService;
import com.zmc.common.exception.base.WebDisplayException;
import com.zmc.common.utils.token.AuthTokenService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author：zmc
 * @Date：2025/1/18 13:41
 */

@Service
public class RoleApplicationServiceImpl implements RoleApplicationService {

    @Autowired
    private SysRoleService roleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;
    @Autowired
    private AuthTokenService authTokenService;


    @Override
    @Transactional
    public void addRole(SysRoleEntity role) {
        //前置检查
        roleFrontCheck(role);
        //添加角色
        role.setCreateBy(authTokenService.getUserInfo().getUsername());
        roleService.save(role);
        //添加权限
        updateMenuList(role);
    }

    @Override
    @Transactional
    public void updateRole(SysRoleEntity role) {
        //前置检查
        roleFrontCheck(role);
        //删除旧权限
        sysRoleMenuService.deleteByRoleId(role.getRoleId());
        //更新角色
        role.setUpdateBy(authTokenService.getUserInfo().getUsername());
        roleService.updateById(role);
        //更新权限
        updateMenuList(role);
    }

    @Override
    @Transactional
    public void removeRole(Long roleId) {
        //删除角色关联菜单
        sysRoleMenuService.deleteByRoleId(roleId);
        //删除角色
        roleService.removeById(roleId);
    }

    public void roleFrontCheck(SysRoleEntity role) {
        if (!roleService.checkRoleNameUnique(role)) {
            throw new WebDisplayException(ErrorCodeConstants.ROLE_PERMISSION_EXCEPTION);
        } else if (!roleService.checkRoleKeyUnique(role)) {
            throw new WebDisplayException(ErrorCodeConstants.ROLE_PERMISSION_EXCEPTION);
        } else if (CollectionUtils.isEmpty(role.getMenuIds())) {
            throw new WebDisplayException(ErrorCodeConstants.ROLE_PERMISSION_EXCEPTION);
        }
    }


    @Transactional
    public void updateMenuList(SysRoleEntity role) {
        List<SysRoleMenuEntity> list = new ArrayList<>();
        role.getMenuIds().forEach(menuId -> {
            SysRoleMenuEntity entity = new SysRoleMenuEntity();
            entity.setRoleId(role.getRoleId());
            entity.setMenuId(menuId);
            list.add(entity);
        });
        sysRoleMenuService.insertBatch(list);
    }

}
